package com.ssyx.product.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ssyx.common.exception.SsyxException;
import com.ssyx.common.result.ResultCodeEnum;
import com.ssyx.product.properties.MinioProperties;
import com.ssyx.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * ClassName:FileUploadServiceImpl
 * Description:
 *
 * @Author kay
 * @Create 2024/4/28 20:16
 * @Version 1.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try {
            // 创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 创建bucket
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            }

            //获取上传文件名称
            //1.每个上传文件名称唯一的
            //2.根据当前日期对上传文件进行分组
            //文件夹名/UUID+文件名 文件夹名用当前日期代替
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String filename =dateDir+"/"+uuid+file.getOriginalFilename();

            //文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                            .object(filename)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());
            //获取上传文件在minio中的路径
            String url = minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/" + filename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SsyxException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
